import Http from '../utils/http.js'

class ClassicModel extends Http{
  constructor(props){
    super(props)
  }
  getLatest(callback){
    this.request({
      url: '/classic/latest',
      // url: '/latest.json',
      success: res=>{
        callback(res)
        this._setLatestIndex(res.index)
        let key = this._getKey(res.index)
        wx.setStorageSync(key, res)
      }
    })
  }
  getClassic(index, nextOrprevious, sCallback){
    // 缓存中寻找 or API写入
    // Key 确定key
    let key = nextOrprevious == "next" ? this._getKey(index+1) : this._getKey(index-1)
    let classic = wx.getStorageSync(key)
    if (!classic){
      this.request({
        url: "/classic/" + index + "/" + nextOrprevious,
        success: res=>{
          wx.setStorageSync(key, res)
          sCallback(res)
        }
      })
    }else {
      sCallback(classic)
    }
  }
  isFirst(index){
    return index === 1 ? true : false
  }
  isLatest(index){
    let latestIndex = this._getLatestIndex()
    return index == latestIndex ? true : false
  }
  _setLatestIndex(index){
    wx.setStorageSync("latest", index)
  }
  _getLatestIndex(){
    let index = wx.getStorageSync("latest")
    return index
  }
  _getKey(index){
    let key = 'classic-' + index
    return key
  }
}

export default ClassicModel
